<!-- 书籍信息页面 -->
{% extends "base.html" %}
{% block title %}书籍信息{% endblock %}
{% block content %}
<link rel="stylesheet"  type="text/css" href="{{ url_for('static', filename='css/button.css') }}">
<style>
    body {
        background-color: #f7f7f7;
    }
    h2 {
        text-align: center;
    }
    .container {
        background-color: #fff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    .card-header {
        background-color: #007bff;
        color: white;
    }
    .table th {
        font-size: 18px;
        font-weight: bold;
        border-top: none;
    }
    .table td {
        font-size: 14px;
        border-top: none;
    }
    .table-striped tbody tr:nth-of-type(odd) {
        background-color: rgba(0, 123, 255, 0.1);
    }
    .table-striped tbody tr:nth-of-type(even) {
        background-color: rgba(0, 123, 255, 0.05);
    }
    /* 隐藏默认的对话框 */
    dialog {
            display: none;
    }
    /* 当对话框可见时显示 */
    dialog[open] {
        display: block;
        position: fixed;
        top: 55%;
        left: 20%;
        transform: translate(-50%, -50%);
        background-color: #fff;
        border: 1px solid #ccc;
        border-radius: 0.5rem;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        border-radius: 8px;
        width: 260px;
        max-width: 90%;
        z-index: 1000;
        flex-direction: column;
        align-items: center;
        text-align: center;
    }
    dialog p {
        font-family: Arial, sans-serif; /* 设置字体家族 */
        font-size: 14px; /* 设置字体大小 */
        font-weight: bold; /* 设置字体粗细 */
        font-style: normal; /* 设置字体样式 */
        margin: 0 0 15px;
    }
    dialog button[value='error'] {
        background-color: #e74c3c;
        color: white;
        border: none;
        padding: 6px 12px;
        border-radius: 6px;
        cursor: pointer;
    }
    dialog button[value='success'] {
        background-color: #008CBA;
        color: white;
        border: none;
        padding: 6px 12px;
        border-radius: 6px;
        cursor: pointer;
    }
    dialog button:hover[value='error'] {
        background-color: #c0392b;
    }
    dialog button:hover[value='success'] {
        background-color: #4CAF50;
    }
</style>
<div class="container mt-5">
    <div class="card">

        <!-- 搜索图书表单 -->
        <div class="card-header">
            <h2>书籍信息</h2>
            <form id="searchForm" method="POST" class="mb-1">
                <div class="row g-2">
                    <div class="col">
                        <input type="text" id="searchTitle" placeholder="书名" class="form-control" />
                    </div>
                    <div class="col">
                        <input type="text" id="searchAuthor" placeholder="作者" class="form-control" />
                    </div>
                    <div class="col">
                        <input type="text" id="searchYear" placeholder="出版年份" class="form-control" />
                    </div>
                    <div class="col-auto"> 
                        <button type="button" onclick="searchBooks()" class="btn btn-primary">搜索</button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 添加图书表单 -->
        <div class="card-body">
            <h4>添加新书籍</h4>
            <form id="addForm" class="mb-1">
                <div class="row g-2">
                    <div class="col">
                        <input type="text" id="addTitle" placeholder="书名" class="form-control" required />
                    </div>
                    <div class="col">
                        <input type="text" id="addAuthor" placeholder="作者" class="form-control" required />
                    </div>
                    <div class="col">
                        <input type="text" id="addIsbn" placeholder="ISBN" class="form-control" required />
                    </div>
                    <div class="col">
                        <input type="number" id="addYear" placeholder="出版年份" class="form-control" required />
                    </div>
                    <div class="col">
                        <input type="text" id="addNote" placeholder="备注" class="form-control" />
                    </div>
                    <div class="col-auto"> 
                        <!-- TODO -->
                        <button type="button" onclick="addBook()" class="btn btn-success">添加书籍</button>
                    </div>
                </div>
            </form>
            {%- if error_message %}
            <dialog open>
                <p>{{ error_message }}</p>
                <button value="error" onclick="this.parentNode.close()">关闭</button>
            </dialog>
            {%- endif %}

            <!-- 图书列表 -->
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>创建时间</th>
                        <th>书名</th>
                        <th>作者</th>
                        <th>ISBN</th>
                        <th>出版年份</th>
                        <th>备注</th>
                        <th>更新数据</th>
                        <th>删除数据</th>
                    </tr>
                </thead>
                <tbody id="bookinfos-list">
                    {%- for bookinfo in all_bookinfos %}
                    <tr>
                        <td>{{bookinfo.id}}</td>
                        <td>{{bookinfo.create_time}}</td>
                        <td>{{bookinfo.title}}</td>
                        <td>{{bookinfo.author}}</td>
                        <td>{{bookinfo.isbn}}</td>
                        <td>{{bookinfo.published_year}}</td>
                        <td>{{bookinfo.note}}</td>
                        <td><a href="#" class="btn btn-sm btn-primary custom-btn"  data-id="{{ bookinfo.id }}">修改</a></td>
                        <td><a href="#" class="btn btn-sm custom-del-btn"  data-id="{{ bookinfo.id }}">删除</a></td>
                    </tr>
                    {%- endfor %}
                </tbody>
            </table>
        </div>

        <div id="updateModal" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; z-index: 1000;">
            <form id="updateForm">
                <input type="hidden" id="updateId" />
                <input type="text" id="updateTitle" placeholder="书名" class="form-control mb-2" required />
                <input type="text" id="updateAuthor" placeholder="作者" class="form-control mb-2" required />
                <input type="text" id="updateIsbn" placeholder="ISBN" class="form-control mb-2" required />
                <input type="number" id="updateYear" placeholder="出版年份" class="form-control mb-2" required />
                <input type="text" id="updateNote" placeholder="备注" class="form-control mb-2" />
                <button type="submit" class="btn btn-success">保存修改</button>
            </form>
            <button id="closeModal" class="btn btn-secondary mt-2">关闭</button>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    // 定义搜索函数
    async function searchBooks() {
        // 获取输入框的值
        const title = document.getElementById("searchTitle").value;
        const author = document.getElementById("searchAuthor").value;
        const year = document.getElementById("searchYear").value;
        // 构造请求体
        const searchData = {
            title: title,
            author: author,
            published_year: year,
        };
        try {
            // 使用 Axios 发送 POST 请求
            const response = await axios.post("/search_books", searchData);
            // 处理响应数据
            const books = response.data;
            renderBookList(books);
        } catch (error) {
            console.error("搜索失败:", error);
            alert("搜索失败，请稍后再试！");
        }
    }

    function renderBookList(books) {
        const tbody = document.getElementById("bookinfos-list");
        tbody.innerHTML = ""; // 清空表格内容

        books.forEach(book => {
            const row = `
                <tr>
                    <td>${book.id}</td>
                    <td>${book.create_time}</td>
                    <td>${book.title}</td>
                    <td>${book.author}</td>
                    <td>${book.isbn}</td>
                    <td>${book.published_year}</td>
                    <td>${book.note || ""}</td>
                    <td><a href="#" class="btn btn-sm btn-primary custom-btn" data-id="${book.id}">修改</a></td>
                    <td><a href="#" class="btn btn-sm custom-del-btn" data-id="${book.id}">删除</a></td>
                </tr>
            `;
            tbody.innerHTML += row;
        });
    }

    // 定义添加函数
    async function addBook() {
        // 获取输入框的值
        const title = document.getElementById("addTitle").value;
        const author = document.getElementById("addAuthor").value;
        const isbn = document.getElementById("addIsbn").value;
        const published_year = document.getElementById("addYear").value;
        const note = document.getElementById("addNote").value;

        // 构造请求体
        const searchData = {
            title: title,
            author: author,
            isbn: isbn,
            published_year: published_year,
            note: note
        };
        try {
            // 使用 Axios 发送 POST 请求
            const response = await axios.post("/add_books", searchData);
            // 处理响应数据
            const books = response.data;
            renderBookList(books);
        } catch (error) {
            console.error("添加失败:", error);
            alert("添加失败，请稍后再试！");
        }
    }

    // 删除按钮的点击事件
    document.addEventListener("click", async (event) => {
        if (event.target.classList.contains("custom-del-btn")) {
            const bookId = event.target.getAttribute("data-id");

            if (confirm(`确定要删除 ID 为 ${bookId} 的书籍吗？`)) {
                try {
                    await axios.delete(`/delete_bookinfo/${bookId}`);
                    alert("删除成功！");
                    location.reload(); // 刷新页面以更新列表
                } catch (error) {
                    console.error("删除失败:", error);
                    alert("删除失败，请稍后再试！");
                }
            }
        }
    });

    // 修改按钮的点击事件
    document.addEventListener("click", async (event) => {
        if (event.target.classList.contains("custom-btn")) {
            const bookId = event.target.getAttribute("data-id");

            try {
                // 获取当前书籍的信息
                const response = await axios.get(`/getbookinfo/${bookId}`);
                const book = response.data;

                // 弹出模态框并填充表单（假设你有一个模态框）
                showUpdateModal(book);
            } catch (error) {
                console.error("获取书籍信息失败:", error);
                alert("获取书籍信息失败，请稍后再试！");
            }
        }
    });

    // 显示修改模态框（假设你有一个模态框）
    function showUpdateModal(book) {
        const modal = document.getElementById("updateModal");
        const updateForm = document.getElementById("updateForm");

        // 填充表单
        updateForm.querySelector("#updateId").value = book.id;
        updateForm.querySelector("#updateTitle").value = book.title;
        updateForm.querySelector("#updateAuthor").value = book.author;
        updateForm.querySelector("#updateIsbn").value = book.isbn;
        updateForm.querySelector("#updateYear").value = book.published_year;
        updateForm.querySelector("#updateNote").value = book.note;

        // 显示模态框
        modal.style.display = "block";

        // 提交修改表单
        updateForm.onsubmit = async (e) => {
            e.preventDefault();

            const updatedBook = {
                title: updateForm.querySelector("#updateTitle").value,
                author: updateForm.querySelector("#updateAuthor").value,
                isbn: updateForm.querySelector("#updateIsbn").value,
                published_year: parseInt(updateForm.querySelector("#updateYear").value),
                note: updateForm.querySelector("#updateNote").value,
            };

            try {
                await axios.put(`/updatebookinfo/${book.id}`, updatedBook);
                alert("修改成功！");
                location.reload(); // 刷新页面以更新列表
            } catch (error) {
                console.error("修改失败:", error);
                alert("修改失败，请稍后再试！");
            }
        };
    }

    // 关闭模态框
    document.getElementById("closeModal").onclick = () => {
        document.getElementById("updateModal").style.display = "none";
    };
</script>
{% endblock %}